//
//  ForgotPwdViewController.m
//  wtshoppingcite
//
//  Created by TW on 15-3-12.
//  Copyright (c) 2015年 TW. All rights reserved.
//

#import "ForgotPwdViewController.h"
@interface ForgotPwdViewController ()<UITextFieldDelegate>

@end

@implementation ForgotPwdViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setTitleView:@"找回密码"];
    [self.navigationController.navigationBar setHidden:NO];
    
    [self.newsPwd setSecureTextEntry:YES];
    
    self.phoneNum.delegate = self;
    self.mcode.delegate = self;
    self.newsPwd.delegate = self;
    
    self.phoneNum.returnKeyType = UIReturnKeyGo;
    self.mcode.returnKeyType = UIReturnKeyGo;
    self.newsPwd.returnKeyType = UIReturnKeyGo;
    
    [_getVerifyCode setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_getVerifyCode setTitle:@"获取验证码" forState:UIControlStateNormal];
    [_getVerifyCode setFont:[UIFont systemFontOfSize:12.0f]];
    
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                          action:@selector(tapAction:)];
    [self.view addGestureRecognizer:tap];
    
    // Do any additional setup after loading the view from its nib.
}


- (void)tapAction:(UITapGestureRecognizer *)tap
{
    [_phoneNum resignFirstResponder];
    [_mcode resignFirstResponder];
    [_newsPwd resignFirstResponder];
    [UIView animateWithDuration:0.3f animations:^{
        
        self.view.transform = CGAffineTransformMakeTranslation(0, 0);
        
    }];
}

-(IBAction)getVerificationCode:(id)sender{
    
    if([self.phoneNum.text isEqualToString:@""]
       ||self.phoneNum.text == nil){
        [Utils showAlertViewWithTitle:@"请填写手机号码！"];
        return;
    }
    if(![Utils checkPhone:self.phoneNum.text]){
        [Utils showAlertViewWithTitle:@"手机号码格式错误,请重新填写手机号码！"];
    }
    else
    {
        
        //GCD实现倒计时
        __block int timeout=60; //倒计时时间
        __block ForgotPwdViewController *weak_self = self;
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
        dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
        dispatch_source_set_event_handler(_timer, ^{
            if(timeout<=0){ //倒计时结束，关闭
                dispatch_source_cancel(_timer);
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    //设置界面的按钮显示 根据自己需求设置
                    weak_self.getVerifyCode.userInteractionEnabled = YES;
                    [self.phoneNum resignFirstResponder];
                    [weak_self.getVerifyCode setTitle:@"获取验证码" forState:UIControlStateNormal];
                    [weak_self.getVerifyCode setBackgroundColor:MAIN_BLUE_COLOR ];
                    
                });
            }else{
                //            int minutes = timeout / 60;
                //            int seconds = timeout % 60;
                NSString *strTime = [NSString stringWithFormat:@"%d秒后",timeout];
                dispatch_async(dispatch_get_main_queue(), ^{
                    //设置界面的按钮显示 根据自己需求设置
                    weak_self.getVerifyCode.userInteractionEnabled = NO;
                    [weak_self.getVerifyCode setTitle:strTime forState:UIControlStateNormal];
                    [weak_self.getVerifyCode setBackgroundColor:MAIN_GRAY_COLOR];
                });
                timeout--;
            }
        });
        dispatch_resume(_timer);
       
            [self getVerificationCode];
        }
}


-(void)getVerificationCode{
    
    NSMutableDictionary *paramDic = [NSMutableDictionary dictionary];
    [paramDic setValue:self.phoneNum.text forKey:@"tel"];
    
    [NetWorkService byRequestWithAPIPrefix:kBaseAppUrl
                              andAPISuffix:kIdentifyCode
                             andHttpMethod:@"POST"
                             andParameters:paramDic
                           andRequestCache:NO
                            andUseParamDic:YES
                       andPostDataEncoding:MKNKPostDataEncodingTypeJSON
                     andRequestFinishBlock:^(BYRequest *request, BYResponse *response)
     {
         
         if(!response.isError){
             NSDictionary *responseDic = request.responseJSON;
             DLog(@"获取验证码  %@",responseDic);
             
         }
         else{
             
             DLog(@"获取验证码失败  %@",response.errorMessage);
         }
     }];
    
}


#pragma mark StepThreeDelegate
-(IBAction)finishAction:(id)sender{
    
    [self.phoneNum resignFirstResponder];
    [self.mcode resignFirstResponder];
    [self.newsPwd resignFirstResponder];
    
    [self showToastMessage:@"请稍等..."];
    
    __weak ForgotPwdViewController *weak_self = self;
    
    NSMutableDictionary *paramDic = [NSMutableDictionary dictionary];
    
    NSString *phone = self.phoneNum.text;
    NSString *verifyCode = self.mcode.text;
    NSString *newPsd = [self.newsPwd.text md5];
    
    if(phone.length == 0){
        [self showAlertView:@"手机/邮箱/用户名不能为空" message:nil];
        return;
    }
    if(verifyCode.length == 0){
        [self showAlertView:@"验证码不能为空" message:nil];
        return;
    }
    if(self.newsPwd.text.length == 0){
        [self showAlertView:@"新密码不能为空" message:nil];
        return;
    }
    
    [paramDic setValue:phone forKey:@"tel"];
    [paramDic setValue:verifyCode forKey:@"mcode"];
    [paramDic setValue:newPsd forKey:@"newPsd"];
   
    
    [NetWorkService byRequestWithAPIPrefix:kBaseAppUrl
                              andAPISuffix:kforgotPwd
                             andHttpMethod:@"POST"
                             andParameters:paramDic
                           andRequestCache:NO
                            andUseParamDic:YES
                       andPostDataEncoding:MKNKPostDataEncodingTypeJSON
                     andRequestFinishBlock:^(BYRequest *request, BYResponse *response){
                         
                         if(!response.isError){
                             NSDictionary *responseDic = request.responseJSON;
                             NSString *msg = [responseDic objectForKey:@"msg"];
                             NSLog(@"%@",msg);
                             DLog(@"获取参数  %@",responseDic);
                             
                             BOOL result= [[responseDic objectForKey:@"result"]boolValue];
                             
                             if (!result) {
                                 [APP_DELEGATE pushLoginViewControllerWithStoryBoardIdentifier:@"LoginViewController" pushIn:self];
                                 
                             }else{
                                 
                                 DLog(@"登录失败 %@",responseDic);
                                 [weak_self showToastMessage:[responseDic objectForKey:@"msg"]];

                             }
                         }
                         else{
                             
                             DLog(@"获取参数失败  %@",response.errorMessage);
                             [weak_self showToastMessage:@"网络错误"];
                         }
                     }];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    [_phoneNum resignFirstResponder];
    [_mcode resignFirstResponder];
    [_newsPwd resignFirstResponder];
    
    return YES;
}


@end
